'use strict';

define([
  'angular',
  'angularAMD',
  'angular-cookies',
], function(ng, angularAMD) {

  angularAMD.controller('MCustomerListCtrl', ['$scope', '$http', '$location', 'ngDialog',
    function($scope, $http, $location, ngDialog) {
      var page = 1;
      var limit = 10;
      var hasMore = true;
      var customerLoading = false;
      loadCustomer();

      var $w = $(window);
      $w.unbind("scroll");
      $w.bind("scroll", function(){
        if($w.scrollTop()+$w.height() > $("#LoadingPlace").offset().top && hasMore && !customerLoading){
          loadCustomer();
        }
      });

      $scope.gotoCustomer = function (customerId){
        return false;
      }

      function loadCustomer() {
        customerLoading = true;
        $http.get("index.php?route=rest/manager/customers&page="+page+"&limit="+limit).then(
          function(result) {
            if (result.data.success) {
              if (1 == page){
                $scope.customerList = result.data.customers;
              }else{
                angular.forEach(result.data.customers, function(customerInfo){
                  $scope.customerList.push(customerInfo);
                })
              }
              if (result.data.customers < limit) {
                $('#LoadingPlace').hide();
                hasMore = false;
              }
              page++;
            }
            customerLoading = false;
          }
        );
      }
    }
  ]);
});
